import { getToken, setToken, removeToken } from '@/utils/auth'
import { _getUserInfo, _login } from '@/api/user'
import { constantRoutes } from '@/router'
import { resetRouter } from '@/router'
const state = {
  token: getToken(),
  userInfo: {},
  routes: constantRoutes // 初始值为静态路由
}
const mutations = {
  setUserToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeUserToken(state) {
    state.token = null
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  setRoutes(state, asyncRoutes) {
    state.routes = [...constantRoutes, ...asyncRoutes] // 不能写state.routes 不然退出登录别的账号时路由会叠加
  }
}
const actions = {
  async login(context, data) {
    // console.log(data)
    const token = await _login(data)
    context.commit('setUserToken', token)
  },
  async getUserInfo(context) {
    const res = await _getUserInfo()
    // console.log(res)
    context.commit('setUserInfo', res)
    return res
  },
  logout(context) {
    context.commit('removeUserToken')
    context.commit('setUserInfo', {})
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
